import { Select, Input } from 'antd'
import React, { useState } from 'react'
import { cloneDeep } from 'lodash-es'
import { v4 as uuidv4 } from 'uuid';
import DynamicTable from '../dynamic-table/index'

export function ManagerTable(props) {
  const { value, onChange, config } = props

  const templateOptions = config.templates.map(item => {
    return {
      value: item.templateName,
      label: item.templateName
    }
  })

  const initRow = () => {
    return {
      key: uuidv4(),
      template: '',
      uuid: ''
    }
  }

  const [data, setData] = useState(cloneDeep(value || []))
  if (data.length == 0) {
    data.push({
      key: uuidv4(),
      template: '',
      uuid: ''
    })
  }

  let timer = null
  const updateValue = (data) => {
    let tempData = [...data]
    setData(tempData)
    if(timer) {
      clearTimeout(timer)
      timer = null
    }
    setTimeout(() => {
      onChange && onChange(tempData)
      timer = null
    }, 500);
  }

  const setFieldData = (index, field, value) => {
    data[index][field] = value
    updateValue(data)
  }

  const columns = [
    {
      title: config.template,
      dataIndex: 'template',
      width: '20%',
      render:(text, record, index) => {
        return <Select options={templateOptions} value={text} onChange={(value) => {
          setFieldData(index, 'template', value)
        }} style={{width: '100%'}}>
        </Select>
      }
    },
    {
      title: '协议内容编码',
      dataIndex: 'uuid',
      width: '20%',
      render:(text, record, index) => {
        return <Input value={text} onChange={(e) => {
          setFieldData(index, 'uuid', e.target.value)
        }} autoComplete='off'/>
      }
    },
  ]

  return (
    <DynamicTable data={data} columns={columns} initRow={ initRow } onChange={updateValue}/>
  )
}

export default ManagerTable
